package com.wlxk.crawler.web.controller;

import com.wlxk.crawler.core.service.IArticleService;
import com.wlxk.crawler.core.service.IGrabService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedOutputStream;

/**
 * @author PanQiangQiang
 * @since 2021-11-03 09:33:21
 */
@Slf4j
@RestController
public class OkController {

    @Resource
    private IGrabService silukeService;

    @Resource
    private IArticleService articleService;

    /**
     * 检查
     *
     * @return
     */
    @GetMapping("/ok")
    public String ok(HttpServletRequest httpRequest) {
        return "ok";
    }

    @GetMapping("/test")
    public String test() {
//        silukeService.grabArticleInfo("https://m.siluke.com/0/110/110847/");
        silukeService.grabArticleInfo("https://m.qishuta.org/Shtml117151.html");
        return "ok";
    }

    @GetMapping("/test1")
    public String test1() {
        silukeService.grabUnSyncChapterInfo();
        return "ok";
    }

    /* 导出txt文件
     * @author
     * @param	response
     * @return
     */
    @GetMapping("/exportTxt")
    public void exportTxt(HttpServletResponse response, Long id) {
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        response.addHeader("Content-Disposition", "attachment;filename="
                + "data.txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            String articleText = articleService.getArticleText(id);
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(articleText.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            //LOGGER.error("导出文件文件出错:{}",e);
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
                //LOGGER.error("关闭流对象出错 e:{}",e);
            }
        }
    }

}
